<?php


namespace app\api\controller;


use app\admin\model\Place;
use app\api\model\MeetDaibanModel;
use app\api\model\MeetDepartmentModel;
use app\api\model\MeetModel;
use app\api\model\MeetPlanModel;
use app\api\model\MeetWeekModel;
use app\common\controller\Api;
use think\Db;

class Plan extends Api
{
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function department()
    {
        $user = $this->auth->getUser();
        $list = MeetDepartmentModel::where("")->field('id,name')->select();
        $list = collection($list)->toArray();
        $meet_id = input('meet_id');
        if(empty($meet_id)){
             $this->error('meet_id必传');
        }
        foreach($list as &$v){
            $map = [
                'user_id' => $user['id'],
                'department_id' => $v['id'],
                'cdate' => date('Y-m-d'),
                'meet_id' => $meet_id,
            ];
            $row = MeetDaibanModel::where($map)->order('id desc')->find();
            $v['content'] = $row?$row['content']:'';
        }
        $this->success('成功',$list);
    }

    public function daiban()
    {
        $user = $this->auth->getUser();
        $input = input();
        $department_id = input('department_id');
        $content = input('content');
        if(empty($department_id) || empty($content)){
             $this->error('内容或部门ID,不能为空');
        }
        $meet_id = input('meet_id');
        if(empty($meet_id)){
            $this->error('meet_id必传');
        }
        $map = [
            'user_id' => $user['id'],
            'department_id' => $department_id,
            'cdate' => date('Y-m-d'),
            'meet_id' => $meet_id,
        ];
        $row = MeetDaibanModel::where($map)->find();
        if($row){
            $model = new MeetDaibanModel();
            $model->allowField(true)->save($input,['id' => $row['id']]);
        }else{
            $input['user_id'] = $user['id'];
            $input['cdate'] = date('Y-m-d');
            $model = new MeetDaibanModel($input);
            $model->allowField(true)->save();
        }
        $this->success('保存成功');
    }

    //交办事项详情
    public function daibanDetail()
    {
        $user = $this->auth->getUser();
        $department_id = input('department_id');
        $meet_id = input('meet_id');
        if(empty($meet_id)){
            $this->error('meet_id必传');
        }
        $map = [
            'user_id' => $user['id'],
            'department_id' => $department_id,
            'cdate' => date('Y-m-d'),
            'meet_id' => $meet_id,
        ];
        $row = MeetDaibanModel::where($map)->find();
        $this->success('成功',$row);
    }

    //删除交办事项
    public function del()
    {
        $user = $this->auth->getUser();
        $department_id = input('department_id');
        $meet_id = input('meet_id');
        if(empty($meet_id)){
            $this->error('meet_id必传');
        }
        $map = [
            'user_id' => $user['id'],
            'department_id' => $department_id,
            'meet_id' => $meet_id,
        ];
        $row = MeetDaibanModel::where($map)->delete();
        $this->success('删除成功',$row);
    }

    public function department2()
    {
        $list = MeetDepartmentModel::where("")
            ->field('id,name')
            ->select();
        $list = collection($list)->toArray();
        foreach($list as &$v){
            $map = [
                'meet_id' => input('meet_id'),
                'department_id' => $v['id'],
            ];

            $row = MeetDaibanModel::where($map)->find();
            $v['jiaodai'] = $row?$row['content']:'';
        }
        $this->success('成功',$list);
    }

    // 添加工作计划
    public function addweekPlan()
    {
        $user = $this->auth->getUser();
        $input = input();
        $department_id = input('department_id');
        $content = input('zhongxin');
        if(empty($department_id) || empty($content)){
            $this->error('内容或部门ID,不能为空');
        }
        if(!empty($input['images'])){
            $input['images'] = htmlspecialchars_decode($input['images']);
        }
        if(!empty($input['files'])){
            $input['files'] = htmlspecialchars_decode($input['files']);
        }
        if(empty($input['date_text'])){
             $this->error('date_text必传');
        }
        $meet_id = input('meet_id');
        if(empty($meet_id)){
            $this->error('meet_id必传');
        }
        //添加计划时间校验
        $meetPlanOffTime = MeetModel::where(['id'=>$meet_id])->value('plan_off_time');
        if(!empty($meetPlanOffTime)&&time()>$meetPlanOffTime){
            $this->error('截止时间为'.date('Y-m-d H:i:s',$meetPlanOffTime));
        }
        $week_num = date("w",strtotime($input['date_text']));
        $input['week_num'] = $week_num;
        $weekarray=array("日","一","二","三","四","五","六");
        if(array_key_exists($week_num,$weekarray)){
            $week_text = '星期'.$weekarray[$week_num];
        }
        if($week_text == '星期日'){
            $week_num = 7;
        }
        $input['week_num'] = $week_num;
        $input['week_text'] = $week_text;
        $map = [
            'meet_id' => $input['meet_id'],
            'department_id' => $input['department_id'],
            'user_id' => $user['id'],
            'date_text' => $input['date_text'],
            'use_time' => $input['use_time'],
        ];
        /*$map2 = [
            'meet_id' => $input['meet_id'],
            'cangsuo' =>  $input['cangsuo'],
            'date_text' =>  $input['date_text'],
            'use_time' => $input['use_time'],
        ];
        $is_chongtu = MeetPlanModel::isChongtu($map2);
        $input['is_chongtu'] = $is_chongtu;*/
        $id = (int)input('id');
        if(!empty($id)){
            $row = MeetPlanModel::get($id);
        } else{
            $row = MeetPlanModel::where($map)->find();
        }
        if($row){
            $model = new MeetPlanModel();
            unset($input['id']);
            $model->allowField(true)->save($input,['id' => $row['id']]);
        }else{
            $input['user_id'] = $user['id'];
            unset($input['id']);
            $model = new MeetPlanModel($input);
            $model->allowField(true)->save();
        }
        $this->success('保存成功');
    }

    public function weekText()
    {
        $input = input();
        $week_num = date("w",strtotime($input['date_text']));
        $input['week_num'] = $week_num;
        $weekarray=array("日","一","二","三","四","五","六");
        if(array_key_exists($week_num,$weekarray)){
            $week_text = '星期'.$weekarray[$week_num];
        } else {
            $week_text = '星期日';
        }
        $data = ['week' => $week_text];
        $this->success('成功',$data);
    }

    //
    public function planDetail()
    {
        $data = MeetPlanModel::get(input('id'));
        $this->success('成功',$data);
    }

    //个人计划列表
    public function plan()
    {
        $input = input();
        if(empty($input['meet_id'])){
            $this->error('会议ID必传');
        }
        $user = $this->auth->getUser();
        $map = [
            'user_id' => $user['id'],
            'meet_id' => input('meet_id'),
        ];
        $list = MeetPlanModel::where($map)->order('week_num asc')->select();
        $list = collection($list)->toArray();
        foreach($list as &$v){

            $v['files'] = json_decode($v['files']);
            $v['images'] = json_decode($v['images']);
           /* $map = [
                'meet_id' => input('meet_id'),
                'cangsuo' => $v['cangsuo'],
                'date_text' => $v['date_text'],
                'use_time' => $v['use_time'],
            ];*/
            /*$row = MeetPlanModel::where($map)->where('user_id',"<>",$user['id'])->order('id desc')->find();
          $v['is_chongtu'] = $row?1:0;*/
            if($v['is_chongtu'] == 0){
                $map2 = [
                    'meet_id' => $input['meet_id'],
                    'cangsuo' =>  $v['cangsuo'],
                    'date_text' =>  $v['date_text'],
                    'use_time' => $v['use_time'],
                ];
                $is_chongtu = MeetPlanModel::isChongtu($map2,$v['id']);
                $v['is_chongtu'] = $is_chongtu;
            }
            $v['date_text'] = date('m.d',strtotime($v['date_text'])).' '.$v['week_text'];

            $user = \app\common\model\User::get($v['user_id']);
            $v['nickname'] = $user?$user['nickname']:'';
            $v['avatar'] = $user?$user['avatar']:'';
        }
        $this->success('成功',$list);
    }

    public function clonePlan()
    {
        $user = $this->auth->getUser();
        $data = MeetPlanModel::get(input('id'));
        if(empty($data)){
             $this->error('参数错误');
        }
        $data = $data->toArray();
        unset($data['id']);
        unset($data['user_id']);
        unset($data['updatetime']);
        unset($data['createtime']);
        $input = $data;
        $input['user_id'] = $user['id'];
        $model = new MeetPlanModel($input);
        $model->allowField(true)->save();
        $this->success('克隆成功',['id' => $model['id']]);
    }

    public function delPlan()
    {
        $row = MeetPlanModel::where('id',input('id'))->delete();
        $this->success('删除成功',$row);
    }

    //添加周反馈
    public function addweek()
    {
        $user = $this->auth->getUser();
        $input = input();
        $meet_id = input('meet_id');
        if(empty($meet_id)){
            $this->error('meet_id必传');
        }
        if (!empty($input['files'])) {
            $input['files'] = htmlspecialchars_decode($input['files']);
        }
        $map = [
            'meet_id' => $input['meet_id'],
            'user_id' => $user['id'],
            'department_id' => $input['department_id'],
        ];
        $row = MeetWeekModel::where($map)->find();
        if($row){
            $model = new MeetWeekModel();
            $model->allowField(true)->save($input,['id' => $row['id']]);
        }else{
            $input['user_id'] = $user['id'];
            $model = new MeetWeekModel($input);
            $model->allowField(true)->save();
        }
        $this->success('保存成功','');
    }

    public function weekDetail()
    {
        $user = $this->auth->getUser();
        $meet_id = input('meet_id');
        if(empty($meet_id)){
            $this->error('meet_id必传');
        }
        $department_id = input('department_id');
        $input = input();
        $map = [
            'meet_id' => $input['meet_id'],
            'user_id' => $user['id'],
        ];
        if(!empty($department_id)){
            $map += [
                'department_id' => $department_id,
            ];
        }
        $data = MeetWeekModel::where($map)->find();
        if(empty($data)){
            $data = [];
            $smap = [
                'department_id' => $department_id,
                'meet_id' => $input['meet_id'],
            ];
            $jiaoban = Db::table('fa_meet_daiban')->where($smap)->find();
            if($jiaoban){
                $data['leader_content'] = $jiaoban['content'];
                $data['department_id'] = $department_id;
                $d = MeetDepartmentModel::get($department_id);
                $data['department_name'] = $d?$d['name']:'';
            }
        }
        $this->success('成功',$data);
    }

    //添加部门周反馈 发起人编辑
    public function adddepartweek()
    {
        $user = $this->auth->getUser();
        $input = input();
        $meet_id = input('meet_id');
        if(empty($meet_id)){
            $this->error('meet_id必传');
        }
        $department_id = input('department_id');
        if(empty($department_id)){
            $this->error('department_id必传');
        }
        if (!empty($input['files'])) {
            $input['files'] = htmlspecialchars_decode($input['files']);
        }
        $map = [
            'meet_id' => $input['meet_id'],
            'department_id' => $input['department_id'],
        ];
        $row = MeetWeekModel::where($map)->find();
        if($row){
            $model = new MeetWeekModel();
            $model->allowField(true)->save($input,['id' => $row['id']]);
        }else{
            $input['user_id'] = $user['id'];
            $model = new MeetWeekModel($input);
            $model->allowField(true)->save();
        }
        $this->success('保存成功','');
    }
    //发起人使用
    public function departWeekDetail()
    {
        $meet_id = input('meet_id');
        if(empty($meet_id)){
            $this->error('meet_id必传');
        }
        $department_id = input('department_id');
        if(empty($department_id)){
            $this->error('department_id必传');
        }
        $input = input();
        $map = [
            'meet_id' => $input['meet_id'],
            'department_id' => $input['department_id'],
        ];
        $data = MeetWeekModel::where($map)->find();
        $this->success('成功',$data);
    }

    public function weeklist()
    {
        $input = input();
        if(empty($input['meet_id'])){
             $this->error('会议ID必传');
        }
        //$list = MeetDepartmentModel::where("id=3")
        $meet_id = $input['meet_id'];
        $meet = MeetModel::get($meet_id);
        $is_edit = $meet&&$meet['role_type'] == 1?1:0;
        $type = input('type');
        if($type == 'last_feedback'){
            //查询一个上周的行政会议
            $meet = MeetModel::where('type',3)->order('id desc')->find();
            if($meet){
                $meet = MeetModel::where('type',3)
                    ->where('id','<',$meet['id'])
                    ->order('id desc')
                    ->find();
                if($meet){
                    $meet_id = $meet['id'];
                }else{
                    $meet_id = '';
                }
            }else{
                $meet_id = '';
            }
            $is_edit = 0;
        }
        $list = MeetDepartmentModel::where("")
            ->field('id,name')
            ->select();
        $list = collection($list)->toArray();
        foreach($list as &$v){
            $v['is_edit'] = $is_edit;
            $map = [
                'meet_id' => $meet_id,
                'department_id' => $v['id'],
            ];
            $week = MeetWeekModel::where($map)->order('id desc')->find();
            $v['week'] = $week?:'';
        }
        $this->success('成功',$list);
    }

    //导出周计划
    public function weeklistExcel()
    {
        $input = input();
        if(empty($input['meet_id'])){
            $this->error('会议ID必传');
        }
        $meet_id = $input['meet_id'];
        $meet = MeetModel::get($meet_id);
        $list = MeetDepartmentModel::where("")
            ->field('id,name')
            ->select();
        $list = collection($list)->toArray();
        foreach($list as &$v){
            $map = [
                'meet_id' => $meet_id,
                'department_id' => $v['id'],
            ];
            $week = MeetWeekModel::where($map)->order('id desc')->find();
            if($week){
                $user = \app\common\model\User::get($week['user_id']);
                $week['nickname'] = $user?$user['nickname']:'';
            }
            $v['week'] = $week?:'';
        }
        $List = $list;
        $newExcel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();  //创建一个新的excel文档
        $newExcel->getActiveSheet()->setTitle($meet['title'].'-周反馈');  //获取当前操作sheet的对象
        $newExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '部门名称')
            ->setCellValue('B1', '领导交办事项')
            ->setCellValue('C1', '完成情况')
            ->setCellValue('D1', '部门小结')
            ->setCellValue('E1', '下周工作内容');

        foreach ($List as $k => $val) {
            $k = $k + 2;
            $newExcel->getActiveSheet()->setCellValue('A' . $k, $val['name'])
                ->setCellValue('B' . $k, !empty($val['week'])?$val['week']['leader_content']:'')
                ->setCellValue('C' . $k, !empty($val['week'])?$val['week']['end_content']:'')
                ->setCellValue('D' . $k, !empty($val['week'])?$val['week']['xiaojie']:'')
                ->setCellValue('E' . $k, !empty($val['week'])?$val['week']['next_content']:'');
        }
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($newExcel, 'Xlsx');
        $filename = 'week'.$meet_id.'.Xlsx';
        $path = '/uploads/'.date('Ymd');
        if (!file_exists('.'.$path)) {
            mkdir('.'.$path,0777, true);
        }
        $filePath = $path.'/' . $filename;
        $writer->save('.'.$filePath);
        $url = request()->domain().$filePath;
        $size = filesize('./'.$filePath);
        $file_name = $filename;
        $data = [
            'filesize' => $size,
            'filename' => $file_name,
            "fullurl" => $url,
        ];
        $this->success('成功',$data);
    }

    public function planlists()
    {

        $input = input();
        if(empty($input['meet_id'])){
            $this->error('会议ID必传');
        }
        $meet_id = $input['meet_id'];
        $type = input('type');
        if($type == 'last_plan'){
            //查询一个上周的行政会议
            $meet = MeetModel::where('type',3)->order('id desc')->find();
            if($meet){
                $meet = MeetModel::where('type',3)
                    ->where('id','<',$meet['id'])
                    ->order('id desc')
                    ->find();
                if($meet){
                    $meet_id = $meet['id'];
                }else{
                    $meet_id = '';
                }
            }else{
                $meet_id = '';
            }
        }
        $map = [
            'meet_id' => $meet_id
        ];
        //$map = "id=4";
        $data = MeetPlanModel::where($map)
            ->field('id,meet_id,week_text,week_num,date_text')
            ->group('week_text')
            ->order('week_num asc')
            ->paginate()
            ->toArray();
        foreach($data['data'] as &$val){
            $val['date_text'] = date('m.d',strtotime($val['date_text'])).' '.$val['week_text'];
            $where = [
                'meet_id' => $val['meet_id'],
                'week_num' => $val['week_num']
            ];
            $list = MeetPlanModel::where($where)->select();
            foreach($list as &$vv){
                $user = \app\common\model\User::get($vv['user_id']);
                $vv['nickname'] = $user?$user['nickname']:'';
                $vv['avatar'] = $user?$user['avatar']:'';
                $vv['files'] = json_decode($vv['files']);
                $vv['images'] = json_decode($vv['images']);
               /* $map = [
                    'meet_id' => input('meet_id'),
                    'cangsuo' => $vv['cangsuo'],
                    'date_text' => $vv['date_text'],
                    'use_time' => $vv['use_time'],
                ];
                $row = MeetPlanModel::where($map)->where('user_id',"<>",$user['id'])->find();
                $vv['is_chongtu'] = $row?1:0;*/
                //if($vv['is_chongtu'] == 0){
                    $map2 = [
                        'meet_id' => $input['meet_id'],
                        'cangsuo' =>  $vv['cangsuo'],
                        'date_text' =>  $vv['date_text'],
                        'use_time' => $vv['use_time'],
                    ];
                    $is_chongtu = MeetPlanModel::isChongtu($map2,$vv['id']);
                    //echo $is_chongtu.PHP_EOL;
                    //echo $vv['user_id'].PHP_EOL;
                    $vv['is_chongtu'] = $is_chongtu;
                //}
            }
            $val['list'] = $list;
        }
        $this->success('成功',$data);
    }

    public function planlistsExcel()
    {
        $input = input();
        if(empty($input['meet_id'])){
            $this->error('会议ID必传');
        }
        $meet_id = $input['meet_id'];
        $meet = MeetModel::get($meet_id);
        $map = [
            'meet_id' => $meet_id
        ];
        $data = MeetPlanModel::where($map)
            ->field('id,meet_id,week_text,week_num,date_text')
            ->group('week_text')
            ->order('week_num asc')->select();
        $data = collection($data)->toArray();
        $new = [];
        $i=0;
        foreach($data as &$val){
            $val['date_text'] = date('m.d',strtotime($val['date_text'])).' '.$val['week_text'];
            $where = [
                'meet_id' => $val['meet_id'],
                'week_num' => $val['week_num']
            ];
            $list = MeetPlanModel::where($where)->order('date_text desc')->select();
            foreach($list as &$vv){
                $user = \app\common\model\User::get($vv['user_id']);
                $vv['nickname'] = $user?$user['nickname']:'';
                $vv['avatar'] = $user?$user['avatar']:'';
                $new[$i] = $vv;
                $i++;
            }
        }
        $List = $new;
        $newExcel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();  //创建一个新的excel文档
        $newExcel->getActiveSheet()->setTitle($meet['title'].'-周计划');  //获取当前操作sheet的对象
        $newExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '日期')
            ->setCellValue('B1', '中心工作')
            ->setCellValue('C1', '牵头部门')
            ->setCellValue('D1', '负责人')
            ->setCellValue('E1', '时间')
            ->setCellValue('F1', '地点')
            ->setCellValue('G1', '备注');
        foreach ($List as $k => $val) {
            $k = $k + 2;
            $date = date('m月d日',strtotime($val['date_text'])).' '.$val['week_text'];
            $newExcel->getActiveSheet()->setCellValue('A' . $k, $date)
                ->setCellValue('B' . $k, $val['zhongxin'])
                ->setCellValue('C' . $k,  $val['department_name'])
                ->setCellValue('D' . $k,  $val['fuzeren'])
                ->setCellValue('E' . $k,  $val['date_text'].' '.$val['use_time'])
                ->setCellValue('F' . $k,  $val['cangsuo'])
                ->setCellValue('G' . $k,  $val['remark']);
        }
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($newExcel, 'Xlsx');
        $filename = 'plan'.$meet_id.'.Xlsx';
        $path = '/uploads/'.date('Ymd');
        if (!file_exists('.'.$path)) {
            mkdir('.'.$path,0777, true);
        }
        $filePath = $path.'/' . $filename;
        $writer->save('.'.$filePath);
        $url = request()->domain().$filePath;
        $size = filesize('./'.$filePath);
        $file_name = $filename;
        $data = [
            'filesize' => $size,
            'filename' => $file_name,
            "fullurl" => $url,
        ];
        $this->success('成功',$data);
    }

    //使用仓所
    public function place()
    {
        //$list = Place::where("")->field('id,place_name')->select();
        $list = Db::table('fa_mrbs_room')->field('id,name as place_name')->select();
        $this->success('成功',$list);
    }


}
